package db

import (
	"blog_api/conf"
	"fmt"
	"github.com/go-redis/redis"
	"strconv"
	"time"
)

var Redis *redis.Client

func init() {
	redis_database, _ := strconv.Atoi(conf.REDIS_DATABASE)
	Redis = redis.NewClient(&redis.Options{
		Addr:     conf.REDIS_HOST,
		Password: conf.REDIS_AUTH,
		DB:       redis_database,
	})
}

func RedisSetInt(key string, value int, expire int) {
	res := Redis.Set(conf.REDIS_PREFIX+key, value, time.Duration(expire)*time.Second)
	fmt.Println("res", res)
}

func RedisGetInt(key string) (int, error) {
	res, err := Redis.Get(conf.REDIS_PREFIX + key).Int()
	if err == nil {
		return res, err
	}
	return 0, err
}

func RedisSetStr(key string, value string, expire int) {
	res := Redis.Set(conf.REDIS_PREFIX+key, value, time.Duration(expire)*time.Second)
	fmt.Println("res", res)
}
func RedisGetStr(key string) (string, error) {
	res := Redis.Get(conf.REDIS_PREFIX + key).Val()
	return res, nil
}

func RedisTtl(key string) (time.Duration, error) {
	res := Redis.TTL(conf.REDIS_PREFIX+key).Val() / 1000000000
	return res, nil
}

func RedisDel(key string) (int64, error) {
	res := Redis.Del(conf.REDIS_PREFIX + key)
	return res.Result()
}

func RedisExists(key string) (int64, error) {
	res := Redis.Exists(conf.REDIS_PREFIX + key)
	return res.Result()
}

func RedisZRevRange(key string, start, stop int64) ([]string, error) {
	res := Redis.ZRevRange(conf.REDIS_PREFIX+key, start, stop)
	return res.Result()
}

func RedisZAdd(key string, members redis.Z) (int64, error) {
	res := Redis.ZAdd(conf.REDIS_PREFIX+key, members)
	return res.Result()
}

func RedisZIncrBy(key string, increment float64, member string) () {
	res := Redis.ZIncrBy(conf.REDIS_PREFIX+key, increment, member)
	fmt.Println(res)
}
